package com.xqboss.apps.listener;

import com.alibaba.fastjson2.JSON;
import com.xqboss.apps.domain.punch.PunchUserRecord;
import com.xqboss.apps.enums.consumer.ConsumerMsgRecordEnum;
import com.xqboss.apps.enums.mq.AppMqNormalEnum;
import com.xqboss.apps.service.consumer.ConsumerTeamMsgRecordService;
import com.xqboss.apps.service.consumer.ConsumerTeamService;
import com.xqboss.apps.service.equipment.EquipmentService;
import com.xqboss.apps.service.punch.PunchUserRecordService;
import com.xqboss.common.core.mq.MqEnum;
import com.xqboss.common.core.mq.MqListener;
import com.xqboss.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class UserPunchListener extends MqListener {

    @Autowired
    private ConsumerTeamService teamService;

    @Autowired
    private ConsumerTeamMsgRecordService consumerTeamMsgRecordService;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private PunchUserRecordService punchUserRecordService;

    @Override
    public MqEnum getEnum() {
        return AppMqNormalEnum.PUNCH_IN;
    }

    @Override
    public ConsumeResult solve(MessageView message) {
        String data = StandardCharsets.UTF_8.decode(message.getBody()).toString();
        List<Long> punchUserRecordIdList = JSON.parseArray(data, Long.class);
        List<PunchUserRecord> recordList = punchUserRecordService.lambdaQuery().in(PunchUserRecord::getId, punchUserRecordIdList).list();
        if (recordList.isEmpty()) {
            return ConsumeResult.SUCCESS;
        }
        PunchUserRecord one = recordList.get(0);
        // 刷新队伍打卡收益
        if(Objects.nonNull(one.getTeamId())){
            teamService.refreshPunchGain(one.getTeamId());
            //增加队伍聊天记录
            consumerTeamMsgRecordService.insertByType(Math.toIntExact(one.getTeamId()), ConsumerMsgRecordEnum.PUNCH, one.getUserId(), null, one.getId());
        }
        // 刷新装备收益
        for (PunchUserRecord record : recordList) {
            boolean update = equipmentService.addIncomeExpByNftNumberId(record.getNftNumberId(), record.getIncome(), record.getBreakageUse());
            if (!update) {
                log.error("更新失败！参数：{}", record);
            }
        }
        return ConsumeResult.SUCCESS;
    }
}
